<template>
    <div class="role-management-container">
        <h2>角色管理</h2>

        <!-- 查询表单 -->
        <el-card class="search-card">
            <el-form :model="queryParams" :inline="true" class="search-form">
                <el-form-item label="角色名称">
                    <el-input v-model="queryParams.keyword" placeholder="请输入角色名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getRoleList">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作按钮 -->
        <div class="operation-buttons" v-permission="['editRole']" v-if="false">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>新增角色
            </el-button>
            <el-button v-if="false" type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
                <el-icon>
                    <Delete />
                </el-icon>批量删除
            </el-button>
        </div>

        <!-- 角色列表 -->
        <el-card class="table-card">
            <el-table :data="roles" border style="width: 100%" @selection-change="handleSelectionChange"
                v-loading="loading">
                <el-table-column v-if="false" type="selection" width="55" />
                <el-table-column prop="roleName" label="角色名称" width="150" />
                <el-table-column prop="description" label="描述" />
                <el-table-column label="操作" width="100" fixed="right" v-permission="['editRole']">
                    <template #default="{ row }">
                        <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
                        <el-button v-if="false" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.pageSize"
                :total="total" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 新增/编辑角色对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @close="closeDialog">
            <el-form :model="formData" label-width="120px" :rules="formRules" ref="roleForm">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="formData.description" placeholder="请输入角色描述" />
                </el-form-item>
                <el-form-item label="权限">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-menu default-active="1" class="el-menu-vertical-demo" @select="handleMenuSelect">
                                <el-menu-item v-for="menu in menus" :key="menu.id" :index="menu.id.toString()"
                                    :class="{ 'is-active': selectedMenu?.id === menu.id }">
                                    {{ menu.name }}
                                </el-menu-item>
                            </el-menu>
                        </el-col>
                        <el-col :span="12">
                            <div v-if="selectedMenu">
                                <el-checkbox v-model="currentViewPermission" :label="selectedMenu.viewPermission"
                                    @change="handlePermissionChange('view', $event)">
                                    查看
                                </el-checkbox>
                                <el-checkbox v-model="currentEditPermission" :label="selectedMenu.editPermission"
                                    @change="handlePermissionChange('edit', $event)" :disabled="!currentViewPermission">
                                    编辑
                                </el-checkbox>
                            </div>
                            <div v-else class="permission-placeholder">
                                请从左侧选择菜单配置权限
                            </div>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDialog">关闭</el-button>
                    <el-button type="primary" @click="submitForm">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getRoleList as fetchRoleList, updateRole, deleteRole } from '@/api/role';
import menusPermissionPage from './menusPermissionPage.js'

// 查询参数
const queryParams = reactive({
    page: 1,
    pageSize: 10,
    keyword: '',
});

// 表单验证规则
const formRules = reactive({
    roleName: [
        { required: true, message: '角色名称不能为空', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
    ],
    description: [
        { max: 100, message: '描述不能超过100个字符', trigger: 'blur' }
    ]
});

// 角色列表数据
const roles = ref([]);
const total = ref(0);
const loading = ref(false);
const selectedIds = ref([]);

// 菜单列表数据
const menus = ref([...menusPermissionPage]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formData = ref({
    id: '',
    roleName: '',
    description: '',
    permissions: [],
});
const roleForm = ref(null);

// 权限相关
const selectedMenu = ref(null);
const currentViewPermission = ref(false);
const currentEditPermission = ref(false);

// 获取角色列表
const getRoleList = async () => {
    loading.value = true;
    try {
        const res = await fetchRoleList(queryParams);
        roles.value = res.data.list.map(item => {
            return {
                ...item,
                permissions: item.permissions != null ? item.permissions != '' ? item.permissions.indexOf(',') != -1 ? item.permissions.split(',') : [item.permissions] : [] : []
            }
        });
        total.value = res.data.total;
    } catch (error) {
        console.error('获取角色列表失败:', error);
        ElMessage.error('获取角色列表失败');
    } finally {
        loading.value = false;
    }
};

// 查询
const handleSearch = () => {
    queryParams.page = 1;
    getRoleList();
};

// 重置查询
const resetSearch = () => {
    queryParams.keyword = '';
    handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
    queryParams.pageSize = val;
    getRoleList();
};

const handleCurrentChange = (val) => {
    queryParams.page = val;
    getRoleList();
};

// 表格选择项改变
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id);
};

// 新增角色
const handleAdd = () => {
    dialogTitle.value = '新增角色';
    formData.value = {
        id: '',
        roleName: '',
        description: '',
        permissions: [],
    };
    selectedMenu.value = null;
    dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row) => {
    dialogTitle.value = '编辑角色';
    formData.value = { ...row };
    // 默认选中第一个菜单
    if (menus.value.length > 0) {
        selectedMenu.value = menus.value[0];
        updatePermissionCheckboxState();
    }
    dialogVisible.value = true;
};

// 删除角色
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm('确认删除该角色吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        await deleteRole(row.id);
        ElMessage.success('删除成功');
        getRoleList();
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
        }
    }
};

// 批量删除
const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}个角色吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        await deleteRole(selectedIds.value.join(','));
        ElMessage.success('批量删除成功');
        selectedIds.value = [];
        getRoleList();
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败');
        }
    }
};

// 提交表单
const submitForm = () => {
    roleForm.value.validate(async (valid) => {
        if (!valid) return;
        let data = { ...formData.value, permissions: formData.value.permissions.join(',') };
        try {
            await updateRole(data);
            ElMessage.success(`${dialogTitle.value}成功`)
            dialogVisible.value = false;
            getRoleList();
        } catch (error) {
            ElMessage.error('操作失败');
        }
    });
};

// 关闭对话框
const closeDialog = () => {
    dialogVisible.value = false;
};

// 选择菜单项
const handleMenuSelect = (index) => {
    const menu = menus.value.find(menu => menu.id.toString() === index);
    selectedMenu.value = menu;
    updatePermissionCheckboxState();
};

// 更新权限复选框状态
const updatePermissionCheckboxState = () => {
    if (selectedMenu.value) {
        currentViewPermission.value = formData.value.permissions.includes(selectedMenu.value.viewPermission);
        currentEditPermission.value = formData.value.permissions.includes(selectedMenu.value.editPermission);
    }
};

// 处理权限变更
const handlePermissionChange = (type, checked) => {
    if (!selectedMenu.value) return;

    const permission = type === 'view'
        ? selectedMenu.value.viewPermission
        : selectedMenu.value.editPermission;

    if (checked) {
        // 添加权限
        if (!formData.value.permissions.includes(permission)) {
            formData.value.permissions.push(permission);
        }

        // 如果是查看权限被选中，确保编辑权限可用
        if (type === 'view') {
            currentEditPermission.value = formData.value.permissions.includes(selectedMenu.value.editPermission);
        }
    } else {
        // 移除权限
        formData.value.permissions = formData.value.permissions.filter(p => p !== permission);

        // 如果是查看权限被取消，同时取消编辑权限
        if (type === 'view') {
            const editPermission = selectedMenu.value.editPermission;
            formData.value.permissions = formData.value.permissions.filter(p => p !== editPermission);
            currentEditPermission.value = false;
        }
    }
};

// 初始化数据
onMounted(() => {
    getRoleList();
});
</script>

<style scoped>
.role-management-container {
    padding: 20px;
}

h2 {
    margin-bottom: 20px;
    color: #333;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
}

.operation-buttons {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.el-menu-vertical-demo {
    width: 100%;
}

.el-menu-item.is-active {
    color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
}

.permission-placeholder {
    color: var(--el-text-color-secondary);
    font-size: 14px;
    padding: 20px;
    text-align: center;
}
</style>
